<script setup lang="ts">
import { reactive, ref, unref, watch, computed } from 'vue'
import { Form } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElCheckbox, ElFormItem, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { loginApi } from '@/api/login'
import { constantRouterMap } from '@/router'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { FormSchema } from '@/types/form'
import { useBasicStoreWithOut } from '@/store/modules/basic'
import CaptchaGenerator from '@/components/CaptchaGenerator/index.vue'

const { required } = useValidator()

const emit = defineEmits(['to-register', 'to-reseter'])

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const basicStore = useBasicStoreWithOut()

const { currentRoute, addRoute, push } = useRouter()

const { wsCache } = useCache()

const { t } = useI18n()

const rules = {
  username: [required(t('common.required'))],
  password: [required(t('common.required'))]
}

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    }
  }
])

const remember = ref(false)

const { register, elFormRef, methods } = useForm()

const loading = ref(false)

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  const formRef = unref(elFormRef)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      if (
        basicStore.getIsLoginCaptcha &&
        (!compareText.value ||
          compareText.value.replace(/^\s+|\s+$/g, '').toUpperCase() !=
            captchaText.value.toUpperCase())
      ) {
        ElMessage.error('请输入正确的验证码')
        return
      }
      loading.value = true
      const { getFormData } = methods
      const formData = await getFormData<UserType>()
      try {
        const data = await loginApi(formData)
        const token = data?.data?.token
          ? `${data?.data?.tokenHead}${data?.data?.token}`
          : data.token
        if (token) {
          await permissionStore.setToken(token)
          wsCache.set(appStore.getToken, token)
          // const res = await getUserInfo()
          await permissionStore.fetchUserInfo()
          wsCache.set(appStore.getUserInfo, permissionStore.getUserInfo)
          // 是否使用动态路由
          if (appStore.getDynamicRouter) {
            getRole()
          } else {
            await permissionStore.generateRoutes('none').catch(() => {})
            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({
              path: redirect.value || permissionStore.addRouters[0].path
            })
          }
        }
      } catch (e) {
        if (basicStore.getIsLoginCaptcha) {
          compareText.value = ''
          generatorRef.value?.generateCaptcha()
        }
      } finally {
        setTimeout(() => {
          loading.value = false
        }, 1000)
      }
    }
  })
}

// 获取角色信息
const getRole = async () => {
  await permissionStore.fetchConfigs()
  await permissionStore.fetchUserInfo()
  const allRoutes = [...constantRouterMap, ...permissionStore.getAddRouters]
  // 是否使用动态路由
  allRoutes.forEach((route) => {
    addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
  })
  permissionStore.setIsAddRouters(true)
  push({
    path: permissionStore.getFirstPath || redirect.value || permissionStore.addRouters[0].path
  })
}

// 去注册页面
const toRegister = () => {
  emit('to-register')
}

// 去重置页面
const toReseter = () => {
  emit('to-reseter')
}

const isRegistration = computed(() => basicStore.getLogin?.registration)

const captchaText = ref('')
const compareText = ref('')
const generatorRef = ref()
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="register"
  >
    <template #title>
      <h2 class="text-2xl font-bold text-center w-[100%]">{{ t('login.login') }}</h2>
    </template>

    <template #tool>
      <div
        v-if="basicStore.getIsLoginCaptcha"
        class="flex justify-between items-center w-[100%]"
        style="margin-bottom: 22px"
      >
        <ElFormItem label="验证码">
          <div class="flex">
            <el-input v-model="compareText" placeholder="请输入验证码" />
            &nbsp;&nbsp;
            <CaptchaGenerator ref="generatorRef" v-model="captchaText" :length="4" />
          </div>
        </ElFormItem>
      </div>
      <div class="flex justify-between items-center w-[100%]">
        <ElCheckbox v-model="remember" :label="t('login.remember')" size="small" />
        <el-link
          v-if="basicStore.getLogin?.showForgotPassword !== false"
          style="line-height: 25px"
          size="small"
          @click="toReseter"
          >忘记密码</el-link
        >
      </div>
    </template>

    <template #login>
      <div class="w-[100%]">
        <ElButton :loading="loading" type="primary" class="w-[100%]" @click="signIn">
          {{ t('login.login') }}
        </ElButton>
      </div>
      <div class="w-[100%] mt-15px" v-if="isRegistration">
        <ElButton class="w-[100%]" @click="toRegister">
          {{ t('login.register') }}
        </ElButton>
      </div>
    </template>
  </Form>
</template>

<style lang="less" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
</style>
